$(function(){
    //获取到当前的currentCity，如果没有，获取一个固定设置值
    var currentCity=SYS_GLOBAL_CONFIG.getCurrentCity("currentCity");
    var l_s;
    if(window.localStorage){
        l_s=window.localStorage;      
    }else{
        l_s={};
    }
    //条状到不同的搜索页面
    $(".c-ul li").on("click",function(){
        var link=$(this).find("a").attr("data-link");
        var flag_value;
        if($("#centerHistory").css("display")=="block"){
            l_s.search_state=1;
        }else{
            l_s.search_state=0;
        }
        location.href="./"+link+".html?currentCity="+currentCity;
    });
    console.log("abs"+l_s.search_state);
    //请求url
    var url=SYS_GLOBAL_CONFIG.reqUrl,
    asyn="true",
    type="post";
    var serviceId=0;
    var productType="SERVICE";
    var address=currentCity;//当前城市名
    var areas=""||address;//当前街道
    var currentPage=1;//默认为第一页
    var totalPage=1;//默认总页数
    var resType="1"//默认
    var userId="";//用户id
    var areaId="";//地区id
    var productName="";
    var show_count=5;//默认显示数据个数
    var dataService=req_func(areaId,userId,productType,address,serviceId,resType,currentPage,show_count,productName);
    //ajax请求数据的共用方法
    function getData(url,dataService,call_func,asyn,type){
        console.log(dataService);
        $.ajax({
            url:url,
            type:type,
            datatype:"json",
            contentType:"application/json",
            data:dataService,
            async:asyn,
            success:function(data){
                call_func(data);  
            },
            error:function(msg){
                console.log(msg);
//                location.href="./error.html";
            }   
        });        
    }
    //请求参数
    function req_func(a_Id,u_Id,p_Type,addr,s_Id,r_Type,cur_Page,s_count,p_name){
        return JSON.stringify({
            "code":"getLocalService",
            "version":"1.0",
            "data":{
                    "areaId":a_Id,
                    "userId":u_Id,
                    "productType":p_Type,
                    "address":addr,
                    "serviceId":s_Id,
                    "resType":r_Type,
                    "currentPage":cur_Page,
                    "showCount":s_count,
                    "productName":p_name
                }    
        });
    }
    //阻止滚动
    var unScroll=function(){
        $('html,body').css({"height":"100%","overflow":"hidden"});
//        $('body').css({"height":"100%","overflow":"hidden"});       
    }
    //允许滚动
    var doScroll=function(){
        $('html,body').css({"height":"auto","overflow":"auto"});
//        $('body').css({"height":"auto","overflow":"auto"});  
    }
    //设置页面滚动
    function setScroll(ele){
        console.log(ele);
        console.log("aa11"+$(ele).css("display"));
        if($(ele).css("display")=="block"){
            unScroll();//阻止滚动
        }else{
            doScroll();//允许滚动
        }
    }
    function call_func1(data){
        console.log(data);
        var datas2=data.data.datas;
        var len2=data.data.datas.length;
        totalPage=data.data.totalPage;//总页数
        var li="";
        for(var i=0;i<len2;i++){
            var pic="";
            var fulladdress=datas2[i].address;
            var addr=fulladdress.split(" ");
            var imgsLen=datas2[i].serviceImgs.length;
            if(imgsLen>0){
                for(var j=0;j<imgsLen;j++){
                    if(j===3){
                        break;
                    }
                    pic+='<img class="l"  src="'+datas2[i].serviceImgs[j].FULLPATH+'" alt="">'
                 }
            }else{
                pic="";
            }

            if(datas2[i].userAuthStatus==1){
                img1='<img class="img-v" src="./images/vip_icon.png" alt="">';

            }else{
                img1=""; 
            }

            li+='<div class="s-detail" data-productId="'+datas2[i].productId+'">'+
                    '<aside class="l-aside l">'+
                        '<img src="'+datas2[i].userImgPath+'" alt="">'+
                    '</aside>'+
                    '<aside class="r-aside l">'+
                        '<div class="raside-name clear">'+
                            '<div class="pro l">'+
                                '<p class="pro-name">'+datas2[i].productName+'</p>'+
                                 '<i>'+datas2[i].saleprice+'/'+datas2[i].unit+'</i>'+
                                '<p class="user-name"><span class="small-light">'+datas2[i].userName+'</span>'+img1+'<span class="zwl-as">'+addr[2]+'/'+addr[3]+'</span></p>'+
                            '</div>'+
                            '<div class="clears"></div>'+
                        '</div>'+
                        '<p class="raside-explain">'+datas2[i].remark+'</p>'+
                        '<div class="raside-img">'+pic+'<div class="clears"></div>'+
                        '</div>'+
                        '<div class="raside-detail ">'+
                               '<span class="detail-info">'+datas2[i].parentServiceName+'</span>'+
                               '<img class="mag-l20" src="./images/shoucang.png" alt=""><span class="detail-info">'+datas2[i].serviceCollectCount+'</span>'+
                               '<img class="mag-l20"src="./images/liulan.png" alt=""><span class="detail-info">'+datas2[i].viewCount+'</span>'+
                        '</div>'+
                    '</aside>'+
                    '<div class="clears"></div>'+
                '</div>';      
        }
        $(".serviceDetail").append(li);
        $(".currentpage").html(data.data.currentPage);
        $(".s-detail").on("click",function(){
            var productId=$(this).attr("data-productId");
            url="./serviceDetail.html?productId="+productId;
            location.href=url;
        });
        
    }
    //获取附近服务信息
    getData(url,dataService,call_func1,asyn,type);
    
    var defaultColor="#333";
    var changeColor="#36c7b7";
    var htmlSize=parseInt($("html").css("fontSize"));
    var h=parseInt($(".searchServiceBody").css("height"));
    var bottomh=2.5*htmlSize;
    /**
     *阴影控制
     **/
    function shadow(){
        var top=$(this).scrollTop();
        if(top>5*htmlSize){
            $(".shadow-top3725").addClass("topAfter").removeClass("topBefore");
        }else{
            $(".shadow-top3725").removeClass("topAfter").addClass("topBefore");
        }
    }
    $(document).on("scroll",$(this),shadow);
    $(".shadow-top3725").on("click",function(){
        $(this).hide();
        doScroll();
        for(var i=0,len=$(".serviceSelect").length;i<len;i++){
            if($(".serviceSelect")[i].style.display!="none"){
                $(".serviceSelect")[i].style.display="none";
            }
        }
        $(".service-nav-li").find("i").attr("class","arrow-bottom");
        $(".service-nav-li").css("color",defaultColor);
    });
    //点击显示地区s
    $("#area").on("click",function(){
        var classname=$(this).find("i").attr("class");
        console.log(classname);
        var dataCity=JSON.stringify({
            "code":"getDictAreaList",
            "version":"1.0",
            "data":{
                "level":"2",
                "fullName":address
            }
        });
        console.log(classname.indexOf("arrow-bottom")>-1);
        if(classname.indexOf("arrow-bottom")>-1){
            getData(url,dataCity,call_func2,asyn,type);    
        }  
        $("#serviceArea").slideToggle(100,function(){
            setScroll("#serviceArea");
        }).siblings(".serviceSelect").hide();
        handle($(this));
    });
    //服务分类
    function call_func3(data){
        console.log(data);
        console.log("哈哈哈");
        var datas=data.data.serviceTypes;
        var sortLen=datas.length;
        console.log(sortLen);
        var sortStr='<li  data-sort="0" class="sort-li">全部分类</li>';
        for(var i=0;i<sortLen;i++){
            sortStr+='<li data-sort="'+datas[i].serviceId+'" class="sort-li">'+datas[i].serviceName+'</li>';    
        }
        console.log(sortStr);
        $(".sort-nav").html(sortStr);
        //点击当前服务类
        $(".sort-nav .sort-li").on("click",function(){
            $(this).addClass("bgf036c").siblings(".sort-li").removeClass("bgf036c");
            serviceId=parseInt($(this).attr("data-sort"));
            var sort_data=JSON.stringify({
                "code":"getPdOrServTypeList",
                 "version":"1.0",
                 "data":{
                     "parentServiceId":serviceId,
                     "type":"SERVICE",
                     "parentPdTypeId":0
                 }
            });
            if(serviceId==0){
                $("#sort-nav-item").html('<li data-sort="0"  class="sort-li">全部分类</li>');
                $("#sort-nav-item li").on("click",function(){
                    $(".serviceDetail").html("");
                    current_Page=1;
                    var s_data=req_func(areaId,userId,productType,address,serviceId,resType,currentPage,show_count,productName);
                    current_Page=1;
                    $(".sorts-span").html($(this).html());
                    getData(url,s_data,call_func1,asyn,type);
                    $("#serviceArea").hide();
                    $("#serviceOrder").hide();
                    $(".shadow-top3725").hide();                                    $("#sort").css("color",defaultColor).find("i").addClass("arrow-bottom").removeClass("arrow-bottom36c").removeClass("arrow-top36c").removeClass("arrow-top");   
                    $("#serviceSort").slideToggle(100,function(){
                        setScroll("#serviceSort");
                    }).siblings(".shopsSelect").hide();
                    $("#area,#order").css("color",defaultColor).find("i").attr("class","arrow-bottom");
                });
          }else{
                getData(url,sort_data,call_func_sort,asyn,type);
            }
        });
        
    }
    
    /**
     *详细子分类
     **/
    function call_func_sort(data){
        console.log(data);
        var datali="";
        var datas=data.data.serviceTypes;
        var areaLen=datas.length;
        for(var i=0;i<areaLen;i++){
            datali+='<li data-serviceId="'+datas[i].serviceId+'"><span>'+datas[i].serviceName+'</span></li>';
        }
        $("#sort-nav-item").html(datali);
        $("#sort-nav-item li").on("click",function(){
            $(".serviceDetail").html("");
            current_Page=1;
            serviceId=parseInt($(this).attr("data-serviceId"));
            var area_data=req_func(areaId,userId,productType,address,serviceId,resType,currentPage,show_count,productName);
            current_Page=1;//使页面滚动的时候从第一页开始
            $(".sorts-span").html($(this).html());
            getData(url,area_data,call_func1,asyn,type);
            $("#serviceArea").hide();
            $("#serviceOrder").hide();
            $(".shadow-top3725").hide();                                    $("#sort").css("color",defaultColor).find("i").addClass("arrow-bottom").removeClass("arrow-bottom36c").removeClass("arrow-top36c").removeClass("arrow-top");
            $("#serviceSort").slideToggle(100,function(){
                setScroll("#serviceSort");
            }).siblings(".shopsSelect").hide();
                    $("#area,#order").css("color",defaultColor).find("i").attr("class","arrow-bottom");
 
        });         
        
    }
    /**
     *获取当前默认城市下的全部市区
     **/
    function call_func2(data){
        console.log(data);
        var datas=data.data.dictAreas;
        var areaLen=datas.length;
        var cityStr='<li data-areaId="" data-city="" class="area-li bgf036c">全城</li>';
        for(var i=0;i<areaLen;i++){
            cityStr+='<li data-areaId="'+datas[i].areaId+'" data-city="'+datas[i].fullName+'" class="area-li  ">'+datas[i].areaName+'</li>';    
        }
        $(".area-nav").html(cityStr);
        
        $(".area-nav .area-li").on("click",function(){
            $(this).addClass("bgf036c").siblings(".area-li").removeClass("bgf036c");
            var cityname=$(this).attr("data-city");
            areaId=$(this).attr("data-areaId");
            
            console.log(cityname+"==========");
            if(cityname!=""){
                curr_city=cityname;      
            }else{
                curr_city=currentCity; 
            }
            console.log("当前城市"+curr_city);
            var dataArea=JSON.stringify({
                "code":"getDictAreaList",
                "version":"1.0",
                "data":{
                    "level":"3",
                    "fullName":curr_city
                }
            });    
            //获取当前市区下的街道或乡镇
            if(areaId==""){
                 $("#area-nav-item").html('<li data-areaId="" data-area="'+curr_city+'"><span>全城</span></li>');
                 $("#area-nav-item li").on("click",function(){
                        $(".serviceDetail").html("");
                        current_Page=1;
                        //设置当前选择的街道或乡镇
                        $("#curr_City").html($(this).find("span").html());
                        areas=$(this).attr("data-area");
                        var area_data=req_func(areaId,userId,productType,address,serviceId,resType,currentPage,show_count,productName);
                        console.log(area_data);
                        getData(url,area_data,call_func1,asyn,type);
                        console.log("----");
                        $("#serviceSort").hide();
                        $(".shadow-top3725").hide();
                        $("#area").css("color",defaultColor).find("i")
                    .addClass("arrow-bottom").removeClass("arrow-bottom36c").removeClass("arrow-top36c").removeClass("arrow-top");
                        $("#serviceArea").slideToggle(100,function(){
                           setScroll("#serviceArea");
                        }).siblings(".serviceSelect").hide();    $("#sort").css("color",defaultColor).find("i").attr("class","arrow-bottom");
                    });
                }else{
                        getData(url,dataArea,call_func_area,asyn,type);
                }
            });   
    }
    //获取当前市区下的街道或乡镇
    function call_func_area(data){
            console.log(data);
            var datali="";
            var datas=data.data.dictAreas;
            var areaLen=datas.length;
            for(var i=0;i<areaLen;i++){
                datali+='<li data-areaId="'+datas[i].areaId+'" data-area="'+datas[i].fullName+'"><span>'+datas[i].areaName+'</span></li>';
            }
            
            $("#area-nav-item").html(datali);
            $("#area-nav-item li").on("click",function(){
                //设置当前选择的街道或乡镇
                $("#curr_City").html($(this).find("span").html());
                $(".serviceDetail").html("");
                current_Page=1;
                areaId=$(this).attr("data-areaId");
                var area_data=req_func(areaId,userId,productType,address,serviceId,resType,currentPage,show_count,productName);
                console.log(area_data);
                var city=$(this).find("span").html();//当前街道
                $("#currentCity").html(city);
                getData(url,area_data,call_func1,asyn,type);
                console.log("----");
                $("#serviceSort").hide();
                $(".shadow-top3725").hide();
                $("#area").css("color",defaultColor).find("i")
            .addClass("arrow-bottom").removeClass("arrow-bottom36c").removeClass("arrow-top36c").removeClass("arrow-top");
                $("#serviceArea").slideToggle(100,function(){
                    setScroll("#serviceArea");
                }).siblings(".serviceSelect").hide();    $("#sort").css("color",defaultColor).find("i").attr("class","arrow-bottom");
            });
        }

    //点击显示排序
    $("#order").on("click",function(){
        console.log("--------------------------");
        $("#serviceOrder").slideToggle(100,function(){
            setScroll("#serviceOrder");
        }).siblings(".serviceSelect").hide();
        handle($(this));
    });
    
    //点击显示-----------分类
    $("#sort").on("click",function(){
        console.log("分类");
        var classname=$(this).find("i").attr("class");
        console.log(classname);
        var sortData=JSON.stringify({
             "code":"getPdOrServTypeList",
             "version":"1.0",
             "data":{
                 "parentServiceId":0,
                 "type":"SERVICE",
                 "parentPdTypeId":0
             }
         });
        console.log(classname.indexOf("arrow-bottom")>-1);
        
        if(classname.indexOf("arrow-bottom")>-1){
            getData(url,sortData,call_func3,asyn,type);    
        }
        $("#serviceSort").slideToggle(100,function(){
            setScroll("#serviceSort");
        }).siblings(".serviceSelect").hide();
        handle($(this));  
    });
    
    
    
    /**
     *默认排序，最新，热门
     **/
    $(".order-li").on("click",function(){
       current_Page=1;//重置页面，从第一页加载数据
       $(".serviceDetail").html("");//数据重置
       resType=$(this).attr("data-order");
       var order_data=req_func(areaId,userId,productType,address,serviceId,resType,currentPage,show_count,productName);
       console.log(order_data);
       getData(url,order_data,call_func1,asyn,type);
       $("#order .order-span").html($(this).html());
       $(".shadow-top3725").hide();
       $("#order").css("color",defaultColor).find("i")
           .addClass("arrow-bottom").removeClass("arrow-bottom36c").removeClass("arrow-top36c").removeClass("arrow-top");
        $("#serviceOrder").slideToggle(100,function(){
            setScroll("#serviceOrder");
       }).siblings(".serviceSelect").hide();  
    });
    /**
     *点击显示详细分类或者全城信息以及全部服务分类 
     **/   
    function handle(a){
        var $_this=a;
        $_this.css("color",changeColor);
        if($_this.find("i").attr("class")==="arrow-bottom36c"||$_this.find("i").attr("class")==="arrow-bottom"){
            $_this.find("i").attr("class","arrow-top36c");
            $(".shadow-top3725").show();
        }else{
//                $_this.find("i").attr("class","arrow-bottom36c");
            $(".shadow-top3725").hide();
            $_this.css("color",defaultColor).find("i").attr("class","arrow-bottom");
        }
        $_this.siblings("li").css("color",defaultColor).find("i")
            .addClass("arrow-bottom").removeClass("arrow-bottom36c").removeClass("arrow-top36c").removeClass("arrow-top");
    }

    //点击搜索，通过服务名进行筛选数据
    $(".search-right .collect").on("click",function(){
        var val=$("#search-input").val();
        search_func(val);
    });
    /**
     *执行搜索方法
     **/                               
    function search_func(el){
        doScroll();//允许滚动
        $("body").css("overflowX","hidden");
        productName=el;//搜索内容
        var sear_data=req_func(areaId,userId,productType,address,serviceId,resType,currentPage,show_count,productName);  
        console.log(productName);
        var his_data=productName
        localStorage.his_data+=his_data+"/";
        $("#search-input").val("");
        $(".serviceDetail").html("");
        current_Page=1;
        //搜索
        getData(url,sear_data,call_func1,asyn,type);
        var t=setTimeout(function(){
            l_s.search_state=0;
            console.log(l_s.search_state);
            $("#centerHistory").css("display","none");//将搜索隐藏
        },100);          
    }                                                       
    console.log(localStorage.his_data);
    if(localStorage.his_data==undefined){
        localStorage.his_data="";       
    }   
    $("#search-input").on("click",function(){
        if(localStorage.his_data.indexOf("/")>-1){
            var h_data_arr=localStorage.his_data.split("/");
            console.log("--"+h_data_arr.length);
            var h_data_str="";
            var len=h_data_arr.length;
            var f=0;//计数器，判断是否超过5
            for(var i=0,len_index=len-1;len_index>=i;len_index--){
                if(f<5){
                    if(h_data_arr[len_index].trim()!=""){
                        h_data_str+='<li><img class="center-img" src="./images/search_icon.png" alt=""><span class="li-span">'+h_data_arr[len_index]+'</span><i></i></li>';
                        f++;
                    }else{
                        h_data_str+='';
                    }
                }else{
                    break;
                }
            }
            console.log(h_data_str);
            $(".history").html(h_data_str);
        }else{
            localStorage.his_data="";
        }
        console.log(localStorage.his_data+"bbbb");
        
        
        $(".history li").on("click",function(){
            var val=$(this).find("span").html();
            search_func(val);
        })
    
    });
    
    //清除历史记录
    $(".clear-p").on("click",function(){
        localStorage.his_data="";    
        $(".history").html(localStorage.his_data);
        console.log($(".history").html());
    });
    
    var current_Page=1;
    /**
     *滚动加载更多*
     **/
    $(window).scroll(function(){
        totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop())-400;
        $(".data-loading").removeClass("hide").addClass("show");
        if((parseFloat($(document).height())-400)==totalheight){ 
            console.log(totalPage+"---"+current_Page);
            if(totalPage>current_Page){
                current_Page+=1;
                var data_p=req_func(areaId,userId,productType,address,serviceId,resType,current_Page,show_count,productName);//传入的为一个current_Page 不同于其他的currentPage
                getData(url,data_p,call_func1,asyn,type);    
            }else{
                $(".data-loading").html("已加载全部");
            }
        } 
     });     
    
});
